package main

import (
	"fmt"
	"github.com/go-martini/martini"
	"github.com/howeyc/fsnotify"
	"net/http"
	"path/filepath"
	// "time"
	"os"
	// "syscall"
	// "os/exec"
	_ "net/http/pprof"
	"runtime"
	"server"
	"server/conf"
	"strconv"
)

var DEBUG, _ = strconv.ParseBool(conf.GET["config"]["DEBUG"])
var PPROF, _ = strconv.ParseBool(conf.GET["config"]["PPROF"])

func watch(p string) {
	path := p
	files := make([]string, 0)
	filepath.Walk(path+"src/server", func(filename string, fi os.FileInfo, err error) error { //遍历目录
		if fi.IsDir() { // 忽略目录
			files = append(files, filename)
		}
		return err
	})
	watcher, err := fsnotify.NewWatcher()
	if err != nil {
		fmt.Println(err)
	}

	go func() {
		for {
			select {
			case name := <-watcher.Event:
				fmt.Println("Chanage:", name)
				os.Exit(0)
			case err := <-watcher.Error:
				fmt.Println(err)
			}
		}
	}()
	// watcher.Watch(p)
	for _, i := range files {
		watcher.Watch(i)
	}
}

func main() {

	var MULTICORE int = runtime.NumCPU() * 2 //number of core
	runtime.GOMAXPROCS(MULTICORE)            //running in multicore

	port := os.Args[1]

	m := server.M
	server.M.NotFound(func(res http.ResponseWriter) string {
		res.WriteHeader(200)
		return "404 NOT FOUND"
	})
	if DEBUG {
		watch("./")
		martini.Env = "development"
	} else {
		martini.Env = "production" //生成环境设置
	}

	if PPROF {
		go func() {
			fmt.Println("start pprof")
			http.HandleFunc("/gc", func(w http.ResponseWriter, req *http.Request) {
				runtime.GC()
			})
			fmt.Println(http.ListenAndServe(conf.GET["config"]["PPROF_PORT"], nil))
		}()
	}

	m.RunOnAddr(port)

	// server := http.Server{
	// 	Addr:           port,
	// 	Handler:        m,
	// 	ReadTimeout:    32 * time.Second,
	// 	WriteTimeout:   32 * time.Second,
	// 	MaxHeaderBytes: 1 << 20,
	// }
	// server.ListenAndServe()

	// execSpec := &syscall.ProcAttr{
	// 	Env:   os.Environ(),
	// 	Files: []uintptr{os.Stdin.Fd(), os.Stdout.Fd(), os.Stderr.Fd()},
	// }
	// // fork, err :=
	// fork, err := syscall.ForkExec(os.Args[0], os.Args, execSpec)

	// if os.Getppid() != 1 {
	// 	filePath, _ := filepath.Abs(os.Args[0]) //将命令行参数中执行文件路径转换成可用路径
	// 	cmd := exec.Command(filePath, os.Args[1:]...)
	// 	//将其他命令传入生成出的进程
	// 	cmd.Stdin = os.Stdin //给新进程设置文件描述符，可以重定向到文件中
	// 	cmd.Stdout = os.Stdout
	// 	cmd.Stderr = os.Stderr
	// 	cmd.Start() //开始执行新进程，不等待新进程退出
	// 	return
	// }

}
